package com.tj.collection.application;

import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.base.services.redis.TimeConsts;
import com.fqgj.common.utils.RandomUtil;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.tj.collection.bean.RedisKey;
import com.tj.collection.db.admin.dao.AdminDAO;
import com.tj.collection.db.admin.entity.AdminEntity;
import com.tj.collection.db.domain.Admin;
import com.tj.collection.db.service.impl.AdminLoginService;
import com.tj.collection.integration.MessageIntegrationService;
import com.tj.collection.utils.ConfigUtil;
import com.tj.collection.utils.MessageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * Created by xiatian on 2017/10/16.
 */
@Component
public class AdminApplication {

    private static final Log log = LogFactory.getLog(AdminApplication.class);
    @Autowired
    private AdminDAO adminDAO;
    @Autowired
    private AdminLoginService adminLoginService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MessageIntegrationService messageIntegrationService;
    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private MessageUtils messageUtils;

    /**
     * 后台登录发送短信验证码
     *
     * @param account
     * @return
     */
    public Boolean sendVerifyCode(String account) {
        AdminEntity adminEntity = adminDAO.getByAccount(account);
        if (adminEntity == null || adminEntity.getDeleted()) {
            throw new ApplicationException("The user does not exist!");
        }
        if (StringUtils.isEmpty(adminEntity.getMobile())) {
            throw new ApplicationException("User's phone number is empty, please supplement the user's phone number!");
        }

        //验证码先从缓存中获取 有的话就不要重新生成
        String valueCode = redisClient.get(RedisKey.VERIFY_CODE_KEY + adminEntity.getMobile());
        String verifyCode = StringUtils.isEmpty(valueCode) ? RandomUtil.getVerifyCode(5) : valueCode;
        log.info("验证码生成成功,mobile:{},verifyCode:{}", adminEntity.getMobile(), verifyCode);
        if (configUtil.isServerTest()) {
            verifyCode = "88888";
            log.info("测试环境默认验证码,phone:" + adminEntity.getMobile() + ",code:" + verifyCode);
            Integer second = TimeConsts.HALF_AN_HOUR;
            redisClient.set(RedisKey.VERIFY_CODE_KEY + adminEntity.getMobile(), verifyCode, second);
            return true;
        }

        Map<String, String> replaceParam = Maps.newHashMap();
        replaceParam.put("VERIFY_CODE", verifyCode);
//        Result<Boolean> result = messageIntegrationService.sendMsg(null, adminEntity.getMobile(), "CASHMAMA_0022", replaceParam);
//        if (null != result && result.isSuccess()) {
//            log.info("send verifyCode by new messageCenter success,bizCode:" + "CASHMAMA_0022" + ",phone:" + adminEntity.getMobile() + ",code:" + verifyCode);
//            //短信验证存放在redis中,失效时间30分钟
//            Integer second = TimeConsts.HALF_AN_HOUR;
//            redisClient.set(RedisKey.VERIFY_CODE_KEY + adminEntity.getMobile(), verifyCode, second);
//            return true;
//        } else {
//            log.info("send verifyCode by new messageCenter,bizCode fail:" + "CASHMAMA_0022" + ",phone:" + adminEntity.getMobile() + ",code:" + verifyCode);
//            throw new ApplicationException("Send message authentication code!");
//        }

        return true;

    }

    /**
     * @param admin
     * @param sso   是否单点登录
     * @return
     */
    public String login(Admin admin, boolean sso) {
        if (admin == null) {
            throw new ApplicationException("The user does not exist!");
        }

        //短信验证码登录白名单，加入白名单无需输入验证码即可登录（仅限于测试环境）
        String loginWhiteList = configUtil.getLoginWhiteAccountList();
        if (StringUtils.isNotBlank(loginWhiteList)) {
            String accounts[] = loginWhiteList.split(";");
            for (String account : accounts) {
                if (account.equals(admin.getAccount())) {
                    String token = adminLoginService.adminLogin(admin, "VERIFYCODE", false);
                    return token;
                }
            }
        }

        String valueCode = redisClient.get(RedisKey.VERIFY_CODE_KEY + admin.getMobile());
        String token = adminLoginService.adminLogin(admin, valueCode, sso);
        return token;
    }


}
